<?php

namespace app\admin\controller\outhouse;


use app\admin\model\inventory\Kc;
use app\admin\model\outhouse\RdinrecordList;
use app\common\controller\Backend;
use think\Db;
use think\Exception;

/**
 * 调拨单据管理
 *
 * @icon fa fa-circle-o
 */
class Rdinrecord extends Backend
{

    /**
     * Tpdj模型对象
     * @var
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\outhouse\Rdinrecord;

    }

    public function index()
    {
        $this->model =  new RdinrecordList();

        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['rdinrecord'=>['wareHouse'],'shelves'])
            ->order($sort,$order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    public function add(){

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            if (empty($params['warehouse_id'])) {
                $this->error('没有选择仓库');
            }

            $warehouseCode        = \app\common\model\Warehouse::getNumber(['id'=>$params['warehouse_id']]);
            try {
                Db::startTrans();
                $code                            = 'IC' . uniqid_date_code();
                $params['warehouse_code']        = $warehouseCode;
                $params['code']                  = $code;
                $createtime                      = date('Y-m-d H:i:s');
                $insertData = [
                    'code' => $code,
                    'code_date'=>$params['code_date'],
                    'warehouse_id'=>$params['warehouse_id'],
                    'createtime'=>$createtime
                ];
                //表头
                Db::name('rdinrecord')->insert($insertData);
                //表体
                $this->addList($params);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

            $this->success('', '', json_encode(['action' => 'add']));
        }
        return $this->fetch();
    }

    public function edit($ids = null){
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            if (empty($params['warehouse_id'])) {
                $this->error('没有选择仓库');
            }
            
            try{
                Db::name('rdinrecord_list')->where('code',$params['code'])->delete();//先删后增
                $this->addList($params);
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('', '', json_encode(['action' => 'edit']));
        }

        $code = Db::name('rdinrecord_list')->where(['id'=>$ids])->value('code');
        $list = Db::name('rdinrecord_list')
            ->alias('r')
            ->join('inventory i','i.number=r.cInvCode','left')
            ->join('shelves s','s.id=r.shelves_id','left')
            ->field('r.iQuantity,i.name,i.number,i.specification,i.unit,s.name as shelves_name,r.shelves_id')
            ->where(['r.code' => $code])
            ->select();
          
        $row  = Db::name('rdinrecord')->where(['code'=>$code])->find();
        $this->assign('list_json',json_encode($list));
        $this->assign('row',$row);
        return $this->fetch();
    }

    /*
     * 锁单
     *   */
    public function checkStatus($ids  = null,$check_status=''){
        $value = $this->request->get('value',0);
        if(is_numeric($check_status)){
            $value = $check_status;
        }
        
        $rdinrecordListInfo  = Db::name('rdinrecord_list')->where(['id'=>$ids])->find();

        if(empty($rdinrecordListInfo)){
            $this->error('单据不存在');
        }
        $code = $rdinrecordListInfo['code'];
        $where['code'] = $code;
        $info = Db::name('rdinrecord')->where($where)->find();
        if($info['status']==1){
            $this->error('单据已处理，无法操作');
        }
        
        try {
            Db::startTrans();
            Db::name('rdinrecord')->where(['code'=>$code])->update(['check_status'=>$value]);
            Db::commit();
        }catch (ValidateException|PDOException|Exception $e){
            Db::rollback();
            throw new Exception($e->getMessage());
        }
        
        //非批量，单个点击
        if($check_status === ''){
            $this->success();
        }
    }
    
    public function addList($params){
        $basic_json    = $params['basic'];
        $basic_arr     = json_decode($basic_json, true);
        if (!array_filter(array_map('array_filter', $basic_arr))) {
            throw new Exception('请填写数据');
        }
        
        foreach ($basic_arr as $k => $v) {
            $list[] = [
                'code' => $params['code'],
                'shelves_id' => $v['shelves_id'],
                'row_id' => $v['row_id'],
                'cInvCode' => $v['cInvCode'],
                'iQuantity' => $v['iQuantity'],
                'createtime' => date('Y-m-d H:i:s'),
            ];
        }
        //表体
        Db::name('rdinrecord_list')->insertAll($list);
    }
    
    /*
     * 批量更新
     *   */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        
        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        $check_status = $values['check_status'] + 0;
        Db::startTrans();
        try {
            $idsArr = explode(',', $ids);
            if ($idsArr){
                foreach($idsArr as $id){
                    $this->checkStatus($id,$check_status);
                    $count++;
                }
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }
    
    /*
     * 手动处理单据
     *   */
    public function dealStatus($ids  = null){
        try {
            if(!$ids){
                exception('请选择要处理的记录');
            }
            
            $codeArr  = Db::name('rdinrecord_list')
            ->where([
                'id'=> ['IN',$ids]
            ])
            ->distinct('code')
            ->column('code');
            
            if(!$codeArr){
                exception('找不到单据');
            }
            
            Db::startTrans();
            Db::connect('database.inc')->startTrans();
            
            $model = new \app\admin\model\outhouse\Rdinrecord();
            foreach ($codeArr as $code){
                $info = db('rdinrecord')->where('code',$code)->find();
                if($info['status']==1){
                    exception('存在已处理单据，请核实');
                }
                if($info['check_status']==0){
                    exception('存在待锁单单据，请核实');
                }
                $warehouseCode = Db::name('warehouse')->where(['id'=>$info['warehouse_id']])->value('number');
                $list = Db::name('rdinrecord_list')->where('code',$code)->select();
                //循环其他入库单表体
                foreach ($list as $k=>&$v){
                    Kc::rdRecordUpdateKc($warehouseCode,$info['warehouse_id'],$v['shelves_id'],date('Y-m-d H:i:s'), $v['cInvCode'], $v['iQuantity'], $code, $info['code_date'], 1, 3);
                    $v['wh_code'] = $warehouseCode;
                    $v['code_date'] =$info['code_date'];
                    $model->insertMiddlData($v,'in',$k);//写入中间库
                }
                Db::name('rdinrecord')->where(['code'=>$code])->update(['status'=>1]);
            }
            Db::commit();
            Db::connect('database.inc')->commit();
        }catch (ValidateException|PDOException|Exception $e){
            Db::rollback();
            Db::connect('database.inc')->rollback();
            Db::name('rdinrecord')->where(['code'=>$code])->update(['result'=>$e->getMessage()]);
            $this->error($e->getMessage());
        }
        $this->success();
    }
    
    /*
     * 删除单据
     *   */
    public function del($ids  = null){
        $rdinrecordListInfo  = Db::name('rdinrecord_list')->where(['id'=>$ids])->find();
        
        if(empty($rdinrecordListInfo)){
            $this->error('单据不存在');
        }
        $code = $rdinrecordListInfo['code'];
        $where['code'] = $code;
        $info = Db::name('rdinrecord')->where($where)->find();
        if($info['status']==1){
            $this->error('单据已处理，无法操作');
        }
        if($info['check_status']==1){
            $this->error('单据已锁，请先反锁单据');
        }
    }
}